package com.guomei.service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.guomei.bean.curse.domain.DistributeRecord;
import com.guomei.bean.curse.domain.UserDistributorCourseRel;
import com.guomei.mapper.curse.DistributeRecordMapper;
import com.guomei.mapper.curse.UserDistributorCourseRelMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * 分销服务类
 * 处理支付时的分销逻辑
 */
@Service
@Slf4j
public class DistributionService {
    
    @Resource
    UserDistributorCourseRelMapper userDistributorCourseRelMapper;
    
    @Resource
    DistributeRecordMapper distributeRecordMapper;

    /**
     * 处理支付成功后的分销逻辑
     * 
     * @param studentId 学生ID
     * @param courseId 课程ID
     * @param orderId 订单ID
     * @param actualPayAmount 实际支付金额
     */
    @Transactional
    public void processDistribution(Long studentId, Long courseId, Long orderId, BigDecimal actualPayAmount) {
        log.info("开始处理分销逻辑: studentId={}, courseId={}, orderId={}, actualPayAmount={}", 
                studentId, courseId, orderId, actualPayAmount);
        
        try {
            // 1. 查询学生和课程的分销关系
            UserDistributorCourseRel relation = userDistributorCourseRelMapper.selectByStudentAndCourse(studentId, courseId);
            
            if (relation == null) {
                log.warn("未找到分销关系: studentId={}, courseId={}", studentId, courseId);
                return;
            }
            
            if (relation.getStatus() == 0) {
                log.warn("分销关系已失效: studentId={}, courseId={}", studentId, courseId);
                return;
            }
            
            // 2. 计算分销金额
            BigDecimal distributionRatio = relation.getDistributionRatio();
            if (distributionRatio == null || distributionRatio.compareTo(BigDecimal.ZERO) <= 0) {
                log.warn("分销比例无效: distributionRatio={}", distributionRatio);
                return;
            }
            
            // 分销金额 = 实际支付金额 * 分销比例 / 100
            BigDecimal distributeAmount = actualPayAmount.multiply(distributionRatio).divide(new BigDecimal("100"));
            
            // 3. 创建分销记录
            DistributeRecord record = new DistributeRecord();
            record.setStudentId(studentId);
            record.setDistributorId(relation.getDistributorId());
            record.setCourseId(courseId);
            record.setOrderId(orderId);
            record.setActualPayAmount(actualPayAmount);
            record.setDistributionRatio(distributionRatio);
            record.setDistributeAmount(distributeAmount);
            record.setStatus((short) 0); // 待结算
            record.setCreatedTime(LocalDateTime.now());
            record.setUpdatedTime(LocalDateTime.now());
            
            distributeRecordMapper.insert(record);
            
            log.info("分销记录创建成功: recordId={}, distributeAmount={}", record.getId(), distributeAmount);
            
        } catch (Exception e) {
            log.error("处理分销逻辑失败", e);
            throw new RuntimeException("处理分销逻辑失败", e);
        }
    }

    /**
     * 结算分销记录
     * 
     * @param recordId 分销记录ID
     */
    @Transactional
    public void settleDistributeRecord(Long recordId) {
        log.info("开始结算分销记录: recordId={}", recordId);
        
        try {
            DistributeRecord record = distributeRecordMapper.selectById(recordId);
            if (record == null) {
                log.warn("分销记录不存在: recordId={}", recordId);
                return;
            }
            
            if (record.getStatus() != 0) {
                log.warn("分销记录状态不正确: recordId={}, status={}", recordId, record.getStatus());
                return;
            }
            
            // 更新状态为已结算
            record.setStatus((short) 1);
            record.setSettleTime(LocalDateTime.now());
            record.setUpdatedTime(LocalDateTime.now());
            
            distributeRecordMapper.updateById(record);
            
            log.info("分销记录结算成功: recordId={}", recordId);
            
        } catch (Exception e) {
            log.error("结算分销记录失败", e);
            throw new RuntimeException("结算分销记录失败", e);
        }
    }

    /**
     * 批量结算分销记录
     * 
     * @param recordIds 分销记录ID列表
     */
    @Transactional
    public void batchSettleDistributeRecords(List<Long> recordIds) {
        log.info("开始批量结算分销记录: recordIds={}", recordIds);
        
        for (Long recordId : recordIds) {
            settleDistributeRecord(recordId);
        }
        
        log.info("批量结算分销记录完成");
    }

    /**
     * 取消分销记录
     * 
     * @param recordId 分销记录ID
     */
    @Transactional
    public void cancelDistributeRecord(Long recordId) {
        log.info("开始取消分销记录: recordId={}", recordId);
        
        try {
            DistributeRecord record = distributeRecordMapper.selectById(recordId);
            if (record == null) {
                log.warn("分销记录不存在: recordId={}", recordId);
                return;
            }
            
            if (record.getStatus() == 2) {
                log.warn("分销记录已取消: recordId={}", recordId);
                return;
            }
            
            // 更新状态为已取消
            record.setStatus((short) 2);
            record.setUpdatedTime(LocalDateTime.now());
            
            distributeRecordMapper.updateById(record);
            
            log.info("分销记录取消成功: recordId={}", recordId);
            
        } catch (Exception e) {
            log.error("取消分销记录失败", e);
            throw new RuntimeException("取消分销记录失败", e);
        }
    }
}
